package com.ainge.easystudy.thread;

import java.util.concurrent.TimeUnit;

/**
 * @author: Ainge
 * @Time: 2021/6/12 16:19
 */
public class DeadLockDemo {

    public static void main(String[] args) {
        /**
         * 利用jsp -l
         * jstack pid
         * 来检查死锁
         */
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldLockThead(lockA,lockB),"AAA").start();
        new Thread(new HoldLockThead(lockB,lockA),"BBB").start();
    }

}

class HoldLockThead implements Runnable{

    private final String lockA;
    private final String lockB;

    public HoldLockThead(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(String.format("线程%s\t自己持有%s，尝试获取%s",Thread.currentThread().getName(),lockA,lockB));
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
            }
        }
    }
}
